<!--
 * @description:
 * @author: cuicui
 * @Date: 2023-11-23 21:08:50
 * @LastEditTime: 2023-12-02 09:28:47
 * @LastEditors: cuicui
-->
<template>
  <business-layout title='角色列表'>
    <div class='table-page-search-wrapper' slot='query'>
      <a-row style='height: 40px;'>
        <a-form style='height: 40px;' :form='form' layout='inline' @submit='handleQueryData'>
          <a-col :span='4' style='height: 40px;'>
            <a-form-item>
              <a-input v-decorator="['roleName']" allowClear placeholder='请输入角色名' />
            </a-form-item>
          </a-col>
          <a-col :span='4' style='height: 40px;margin-left: 10px'>
            <a-form-item>
              <a-button type='primary' html-type='submit'>
                <a-icon type='search' />
                查询
              </a-button>
              <a-button html-type='reset' style='margin-left: 10px;' @click='handleResetData'>
                重置
              </a-button>
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
    </div>

    <template slot='btns'>
      <a-button type='primary' icon='plus' @click='handleAdd'>新建</a-button>
    </template>

    <s-table
      ref='table'
      size='default'
      rowKey='id'
      :columns='columns'
      :data='loadData'
      showPagination='auto'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='updatedTime' slot-scope='text, record, index'>
        {{ text | dayjs }}
      </span>
      <span slot='roledesc' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a class='del-link' @click='showDeleteConfirm(record)'>删除</a>
        </template>
      </span>
    </s-table>

    <create-form
      ref='createModal'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @cancel='handleCancel'
      @ok='handleOk'
    />
    <assign
      ref='createAssign'
      :visible='assignVisible'
      :loading='assignLoading'
      @cancel='handleAssignCancel'
      @ok='handleAssignOk'
    />
  </business-layout>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'

import CreateForm from './CreateForm'
import Assign from './assign.vue'
import { findRoleByPage, addRole, updateRole, deleteByRoleId, assignRolePermission } from '@/api/role'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '角色名',
    dataIndex: 'rolename'
  },
  // {
  //   title: '角色编码',
  //   dataIndex: 'roleCode'
  // },
  {
    title: '创建时间',
    dataIndex: 'updatedTime',

    scopedSlots: { customRender: 'updatedTime' }
  },
  {
    title: '备注',
    dataIndex: 'roledesc',
    scopedSlots: { customRender: 'roledesc' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Role',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    Assign
  },
  data() {
    this.columns = columns
    return {
      form: this.$form.createForm(this),
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      assignVisible: false,
      assignLoading: false,
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return findRoleByPage(requestParameters)
          .then(res => {
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {},
  created() {
  },
  computed: {},
  mounted() {
  },
  beforeDestroy() { // 订阅事件记得要取消
  },
  methods: {
    handleResetData() {
      this.queryParam = {}
      this.form.resetFields()
      this.$refs.table.refresh()
    },
    handleAssignCancel() {
      this.assignVisible = false
    },
    handleAssignOk() {
      this.assignVisible = false
    },
    handleQueryData(e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = {
        ...record,
        permissionIds: record.permissionList.map(item => {
          return {
            label: item.permissionName,
            value: item.id
          }
        })
      }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields(async (errors, values) => {
        if (!errors) {
          if (values.id) {
            try {
              const upres = await updateRole(values)
              // 新增
              if (upres) {
                this.visible = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                assignRolePermission({
                  roleId: values.id,
                  permissionIds: values.permissionIds.map(item => item.value)
                }).then(res => {
                  this.$refs.table.refresh()
                  this.$message.success('更新成功')
                })
              }
            } finally {
              this.confirmLoading = false
            }
          } else {
            try {
              const addres = await addRole(values)
              // 新增
              if (addres) {
                this.visible = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                assignRolePermission({
                  roleId: addres.id,
                  permissionIds: values.permissionIds.map(item => item.value)
                }).then(res => {
                  this.$refs.table.refresh()
                  this.$message.success('新增成功')
                })
              }
            } finally {
              this.confirmLoading = false
            }
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    showDeleteConfirm(record) {
      const { $message, $refs } = this
      this.$confirm({
        title: '提示?',
        content: '当前操作不可逆、确定要删除所选角色么？',
        okType: 'danger',
        async onOk() {
          const result = await deleteByRoleId({ roleId: record.id })
          if (result) {
            $message.success(`删除成功`)
            $refs.table.refresh()
          }
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    handleShowAssign() {
      this.assignVisible = true
    },
    handleSub(record) {
      this.$confirm({
        title: '提示?',
        content: '确定要锁定所选角色么？',
        onOk() {
          this.$message.success(`${record.no} 锁定成功`)
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>

